<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部搜索区域 -->
    <div class="sticky top-0 z-10 bg-white shadow-sm">
      <div class="container mx-auto px-4 py-3">
        <div class="flex items-center gap-3">
          <div class="relative flex-1">
            <el-input
                placeholder="搜索服务或护工姓名"
                class="!rounded-button"
                size="large"
                v-model="filterService.name"
            >
              <template #prefix>
                <el-icon class="el-input__icon"><i class="fas fa-search" /></el-icon>
              </template>
            </el-input>
          </div>
          <el-button type="primary"
                     class="!rounded-button whitespace-nowrap"
                     @click="getServices"
          >
            <el-icon class="mr-1"><i class="fas fa-sliders-h" /></el-icon>
            筛选
          </el-button>
        </div>
        <!-- 分类导航 -->
        <div class="mt-3 overflow-x-auto">
          <div class="flex space-x-4 pb-2">
            <div
                @click="selectCategory(null)"
                :class="{
                'text-blue-600 border-b-2 border-blue-600': filterService.categoryId === null,
                'text-gray-600': filterService.categoryId !== null
                }"
                class="px-3 py-2 font-medium text-lg whitespace-nowrap cursor-pointer transition-colors"
            >
              全部分类
            </div>
            <div
                v-for="(category, index) in categories"
                :key="index"
                @click="selectCategory(category.id)"
                :class="{
                'text-blue-600 border-b-2 border-blue-600': filterService.categoryId === category.id,
                'text-gray-600': filterService.categoryId !== category.id
                }"
                class="px-3 py-2 font-medium text-lg whitespace-nowrap cursor-pointer transition-colors"
            >
              {{ category.name }}
            </div>

          </div>
        </div>
      </div>
    </div>
    <!-- 主要内容区 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 服务 -->
      <div class="mb-8">
        <h2 class="text-xl font-semibold mb-4">选择服务</h2>
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          <div
              @click="selectService(null)"
              :class="{
              'bg-blue-100 border-blue-300': filterWorker.serviceId === null,
              'bg-white border-gray-200': filterWorker.serviceId !== null
              }"
              class="border rounded-lg p-4 flex flex-col items-center cursor-pointer transition-colors hover:shadow-md"
          >
            <div
                class="w-12 h-12 mb-3 bg-blue-50 rounded-full flex items-center justify-center"
            ></div>
            <span class="text-sm font-medium">全部服务</span>
          </div>
          <div
              v-for="(service, index) in services"
              :key="index"
              @click="selectService(service.id)"
              :class="{
              'bg-blue-100 border-blue-300': filterWorker.serviceId === service.id,
              'bg-white border-gray-200': filterWorker.serviceId !== service.id
              }"
              class="border rounded-lg p-4 flex flex-col items-center cursor-pointer transition-colors hover:shadow-md"
          >
          <div
            class="w-12 h-12 mb-3 bg-blue-50 rounded-full flex items-center justify-center"
            :style="{
              backgroundImage: 'url(' + SERVER_ADDR + '/upload/' + service.pic + ')',
              backgroundSize: 'cover',
              backgroundPosition: 'center'
            }"
          ></div>
            <span class="text-sm font-medium">{{service.name}}</span>
          </div>
        </div>
      </div>
      <!-- 服务列表 -->
      <div>
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold">推荐护工</h2>
          <el-button text class="text-blue-600">
            查看更多 <el-icon><i class="fas fa-chevron-right" /></el-icon>
          </el-button>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div
              v-for="(worker, index) in workers"
              :key="index"
              class="bg-white rounded-lg shadow-sm overflow-hidden border border-gray-100 hover:shadow-md transition-shadow"
          >
            <div class="p-4">
              <div class="flex items-start">
                <div class="relative mr-4">
                  <img
                      :src="`${SERVER_ADDR}/upload/${worker.picdir}`"
                      class="w-16 h-16 rounded-full object-cover border-2 border-white shadow"
                      alt="护工头像"
                  >
                  <span
                      class="absolute -bottom-1 -right-1 bg-blue-500 text-white rounded-full p-1"
                  >
                  <el-icon class="text-xs"><i class="fas fa-check" /></el-icon>
                </span>
                </div>
                <div class="flex-1">
                  <div class="flex justify-between items-start">
                    <div>
                      <h3 class="font-semibold text-lg">{{ worker.mname }}</h3>
                      <div class="flex items-center mt-1">
                        <el-rate
                            v-model="worker.rating"
                            disabled
                            :max="5"
                            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                            class="mr-2"
                        />
                        <span class="text-gray-500 text-sm">100次服务</span>
                      </div>
                    </div>
                    <el-tag
                        :type="worker.mgender === '男' ? 'primary' : 'danger'"
                        size="small"
                        class="!rounded-button"
                    >
                      {{ worker.mgender }}
                    </el-tag>
                  </div>
                  <div class="mt-2">
                    <el-tag
                        v-for="(service, index) in worker.services"
                        :key="index"
                        type="info"
                        size="small"
                        class="mr-1 mb-1 !rounded-button"
                    >
                      {{ service.name }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <p class="mt-3 text-gray-600 text-sm leading-relaxed">
                工号：{{ worker.mno }}联系方式：{{ worker.mphone }}
              </p>
            </div>
            <div class="px-4 py-3 bg-gray-50 border-t border-gray-100 flex justify-between items-center">
              <div>
              </div>
              <el-button
                  type="primary"
                  class="!rounded-button whitespace-nowrap"
                  @click="showBookingDialog(worker.mid)"
              >
                立即预约
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </main>
    <!-- 底部导航 -->
    <footer class="bg-white border-t mt-8 py-4">
      <div class="container mx-auto px-4">
        <div class="flex justify-between items-center">
          <div class="text-gray-500 text-sm">
            © 2025 养老易 版权所有
          </div>
          <div class="flex space-x-4">
            <el-button text class="text-gray-600" @click="showAppointmentHistory">
              <el-icon class="mr-1"><i class="fas fa-history" /></el-icon>
              预约记录
            </el-button>
            <el-button text class="text-gray-600" @click="scrollToTop">
              <el-icon class="mr-1"><i class="fas fa-arrow-up" /></el-icon>
              返回顶部
            </el-button>
          </div>
        </div>
      </div>
    </footer>
    <!-- 预约对话框 -->
    <el-dialog
        v-model="bookingDialogVisible"
        title="预约服务"
        width="90%"
        :fullscreen="isMobile"
        class="booking-dialog"
    >
      <div v-if="selectedWorker" class="space-y-6">
        <div class="flex items-center">
          <img
              :src="`${SERVER_ADDR}/upload/${selectedWorker.picdir}`"
              class="w-16 h-16 rounded-full object-cover mr-4"
              alt="护工头像"
          >
          <div>
            <h3 class="font-semibold text-lg">{{ selectedWorker.name }}</h3>
            <div class="flex items-center mt-1">
              <el-rate
                  v-model="selectedWorker.rating"
                  disabled
                  :max="5"
                  :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                  class="mr-2"
              />
              <span class="text-gray-500 text-sm">100次服务</span>
            </div>
          </div>
        </div>
        <div>
          <h4 class="font-medium mb-3">选择服务项目</h4>
          <div class="grid grid-cols-2 gap-3">
              {{ selectedService.name }}
          </div>
          <h4 class="font-medium mb-3">选择服务金额</h4>
          <div class="grid grid-cols-2 gap-3">
            {{ selectedService.price }}
          </div>
          <h4 class="font-medium mb-3">选择服务时间</h4>
          <div class="grid grid-cols-2 gap-3">
            {{ selectedService.time}}h
          </div>
        </div>
        <div>
          <h4 class="font-medium mb-3">选择服务日期</h4>
          <el-date-picker
              v-model="bookingDate"
              type="date"
              placeholder="选择日期"
              :disabled-date="disabledDate"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              class="w-full"
          />
        </div>
        <div>
          <h4 class="font-medium mb-3">选择服务时间段</h4>
          <div class="grid grid-cols-3 gap-3">
            <el-button
                v-for="(timeSlot, index) in timeSlots"
                :key="index"
                :type="selectedTimeSlot === index ? 'primary' : ''"
                class="!rounded-button"
                @click="selectTimeSlot(index)"
            >
              {{ timeSlot.label }}
            </el-button>
          </div>
        </div>
        <div v-if="selectedTimeSlot !== null">
          <h4 class="font-medium mb-3">选择具体时间</h4>
          <div class="grid grid-cols-4 gap-3">
            <el-button
                v-for="(time, index) in availableTimes"
                :key="index"
                :type="reservationForm.startTime === bookingDate + ' ' + time ? 'primary' : ''"
                class="!rounded-button"
                @click="selectTime(time)"
            >
              {{ time }}
            </el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bookingDialogVisible = false" class="!rounded-button">取消</el-button>
          <el-button
              type="primary"
              class="!rounded-button whitespace-nowrap"
              @click="confirmBooking"
          >
            确认预约
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="js" setup>
import { ref, computed, onMounted } from 'vue';
import categoryApi from "@/api/admin/categoryApi.js";
import {ElMessage} from "element-plus";
import serviceApi from "@/api/admin/serviceApi.js";
import medicalApi from "@/api/user/medicalApi.js";
import {useTokenStore} from "@/stores/token.js";
import {useUserStore} from "@/stores/user.js";
import reservationApi from "@/api/user/reservationApi.js";

//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
const tokenStore = useTokenStore();
const userStore = useUserStore();
// 分类数据
const categories = ref([]);
// 服务数据
const services = ref([]);
// 护工数据
const workers = ref([]);
// 过滤的条件服务
const filterService = ref({
  name: '',
  categoryId: null,
});
// 过滤员工
const filterWorker = ref({
  serviceId: null
});
// 选择父分类
const selectCategory = (id) => {
  filterService.value.categoryId = id
  getServices()
};
// 选择服务
const selectService = (id) => {
  filterWorker.value.serviceId = id
  getServiceById(id)
  getWorkers()
};
// 预约相关状态
const bookingDialogVisible = ref(false);
const selectedWorker = ref(null);
// 预购表单
const reservationForm = ref({
  serviceId: '',
  startTime: '',
  endTime: '',
  mid: '',
  totalPrice: '',
});
const selectedService = ref(null);
const bookingDate = ref('');
const selectedTimeSlot = ref(null);
// 时间段选项
const timeSlots = ref([
  {
    label: '上午 (8:00-12:00)',
    times: ['08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30']
  },
  {
    label: '下午 (12:00-18:00)',
    times: ['12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30']
  },
  {
    label: '晚上 (18:00-22:00)',
    times: ['18:00', '18:30', '19:00', '19:30', '20:00', '20:30', '21:00', '21:30']
  }
]);
// 可预约的时间段
const availableTimes = computed(() => {
  if (selectedTimeSlot.value === null) return [];
  return timeSlots.value[selectedTimeSlot.value].times;
});
// 禁用过去的日期
const disabledDate = (date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return date < today;
};
// 显示预约对话框
const showBookingDialog = (id) => {
  // 判断是否选中服务
  if (!filterWorker.value.serviceId) {
    ElMessage.warning('请先选择服务');
    return;
  }
  // 查询员工
  medicalApi.selectByMid(id)
      .then(resp => {
        if (resp.code == 10000) {
          selectedWorker.value = resp.data
          selectedWorker.value.rating = 5
          bookingDate.value = '';
          selectedTimeSlot.value = null;
          reservationForm.value.mid = id
          bookingDialogVisible.value = true;
        }
      })
};
// 选择时间段
const selectTimeSlot = (index) => {
  selectedTimeSlot.value = index;
};
// 选择时间
const selectTime = (time) => {
  // 校验参数是否有效
  if (!bookingDate.value || !time) {
    ElMessage.warning("请选择日期和具体时间");
    return;
  }

  // 拼接日期和时间
  const startStr = `${bookingDate.value} ${time}`;
  // 转换为 Date 对象
  const startDate = new Date(startStr.replace(' ', 'T'));
  console.log(startStr)
  // 再次检查日期是否合法
  if (isNaN(startDate.getTime())) {
    ElMessage.error("无效的时间格式，请重新选择");
    return;
  }

  // 获取服务时长（假设 selectedService.value.duration 是以小时为单位）
  const durationHours = selectedService.value?.duration || 1; // 默认 1 小时

  // 计算结束时间
  const endDate = new Date(startDate);
  endDate.setHours(startDate.getHours() + durationHours);

  // 格式化时间为 "YYYY-MM-DD HH:mm"
  const formatTime = (date) => {
    const YYYY = date.getFullYear();
    const MM = String(date.getMonth() + 1).padStart(2, '0');
    const DD = String(date.getDate()).padStart(2, '0');
    const HH = String(date.getHours()).padStart(2, '0');
    const mm = String(date.getMinutes()).padStart(2, '0');
    return `${YYYY}-${MM}-${DD} ${HH}:${mm}`;
  };

  // 设置表单字段
  reservationForm.value.startTime = formatTime(startDate);
  reservationForm.value.endTime = formatTime(endDate);
};


// 确认预约
const confirmBooking = () => {
  reservationApi.insert(reservationForm.value)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success('预约成功！');
          bookingDialogVisible.value = false;
        }else {
          ElMessage.error(resp.msg)
        }
      })
      .catch(error => {
        ElMessage.error('预约失败，请稍后再试');
      });
};

const showAppointmentHistory = () => {
  ElMessage.info('预约记录功能正在开发中');
};
// 检查是否为移动设备
const isMobile = ref(false);
onMounted(() => {
  isMobile.value = window.innerWidth < 768;
  window.addEventListener('resize', () => {
    isMobile.value = window.innerWidth < 768;
  });
});
// 获取护工信息
const getWorkers = () => {
  medicalApi.selectAll(filterWorker.value.serviceId)
      .then(resp => {
        if (resp.code === 10000) {
          workers.value = resp.data;
          workers.value.forEach(worker => {
            worker.rating = 5.0
          })
        }else {
          ElMessage.error(resp.msg)
        }
      })
};
// 获取分类信息
const getCategories = () => {
  let category = {
    parentId: 0,
    categoryType: 1,
  };
  categoryApi.selectByPage(null, null, category)
      .then(resp => {
        if (resp.code === 10000){
          categories.value = resp.data;
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
// 获取服务的信息
const getServices = () => {
  serviceApi.selectByPage(1, 1000,'id','asc', filterService.value)
      .then(resp => {
        if (resp.code === 10000){
          services.value = resp.data.data;
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
// 获取预约的服务信息
const getServiceById = (id) => {
  serviceApi.selectById(id)
      .then(resp => {
        if (resp.code === 10000){
          selectedService.value = resp.data;
          reservationForm.value.serviceId = selectedService.value.id;
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
// 滚动到顶部
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};
getCategories();
getServices();
getWorkers();
</script>
<style scoped>
/* 自定义对话框样式 */
.booking-dialog {
  --el-dialog-border-radius: 12px;
}
.booking-dialog .el-dialog__header {
  border-bottom: 1px solid var(--el-border-color-light);
}
.booking-dialog .el-dialog__body {
  padding: 20px;
}
.booking-dialog .el-dialog__footer {
  border-top: 1px solid var(--el-border-color-light);
  padding: 12px 20px;
}
/* 响应式调整 */
@media (max-width: 768px) {
  .booking-dialog .el-dialog {
    margin: 0;
    max-height: 100vh;
    border-radius: 0;
  }
  .booking-dialog .el-dialog__body {
    padding: 15px;
  }
}
</style>
